package com.loongtech.bi.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.loongtech.core.util.ExcelUtils;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 
 * ClassName: TransferHelper
 * 
 * @Description: 数据传输类
 * @author liuchen
 * @date 2017-5-12 上午11:42:39
 */
public class TransferHelper implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3997437097591974249L;

	protected Map<String, Object> jsonToMap(String params) {
		Map<String, Object> map = JSON.parseObject(params, new TypeReference<Map<String, Object>>() {
		});
		return map;
	}

	private static String htmlEncode(String data) {
		if (data.contains("<")) {
			data = data.replaceAll("<", "&amp;lt;");
		}
		if (data.contains(">")) {
			data = data.replaceAll(">", "&amp;gt;");
		}
		return data;
	}

	protected void printToJson(HttpServletResponse response, String data, String callback) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			String s = callback == null ? data : callback + "('" + data + "')";
			out.println(s);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void printToJson(HttpServletResponse response, Map<?, ?> jsonMap, String callback) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			String s = callback == null ? htmlEncode(JSONArray.toJSONString(jsonMap)) : callback + "('"
					+ htmlEncode(JSONArray.toJSONString(jsonMap)) + "')";
			out.println(s);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void printToStr(HttpServletResponse response, String Str) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			out.println(htmlEncode(Str));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void printToStr(HttpServletResponse response, Object info) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			out.println(htmlEncode(JSONObject.toJSONString(info)));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void printToObject(HttpServletResponse response, Object info, String callback) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json");
			response.setDateHeader("Expires", 0);
			PrintWriter out = response.getWriter();
			String s = callback == null ? info.toString() : callback + "('" + info + "')";
			out.println(s);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void exportExcel(List<List<List<String>>> ldatas, List<String> sheetNames,
			List<List<String>> columnnames, String filename, HttpServletResponse response) throws IOException {
		if (!filename.endsWith(".xls")) {
			filename += ".xls";
		}
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-disposition", "attachment;filename=" + filename);
		response.setBufferSize(5000);
		OutputStream out = response.getOutputStream();
		getExcelWorkbook(ldatas, sheetNames, columnnames).write(out);
		out.flush();
		out.close();
	}

	public Workbook getExcelWorkbook(List<List<List<String>>> ldatas, List<String> sheetNames,
			List<List<String>> columnnames) {
		Workbook workbook = null;
		try {
			workbook = new HSSFWorkbook();
			Map<String, CellStyle> wbStyles = ExcelUtils.getCellStyles(workbook);
			if (ldatas.size() > 0) {

				generalSheet(workbook, wbStyles, sheetNames, columnnames, ldatas);

			} else {
				generalSheet(workbook, wbStyles, "sheet", 0, 0, null, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return workbook;
	}

	private void generalSheet(Workbook workbook, Map<String, CellStyle> wbStyles, List<String> sheetNames,
			List<List<String>> columnnames, List<List<List<String>>> ldatas) {
		int i = 0;

		for (String sheetName : sheetNames) {
			Sheet sheet = workbook.createSheet(sheetName);
			// 设置列宽
			int col = 0;
			if (columnnames != null) {
				for (String columnname : columnnames.get(i)) {
					sheet.setColumnWidth((short) col++, 5000);
				}
			}
			// 创建第一行标题
			Row row = sheet.createRow((short) 0);
			col = 0;
			for (String columnname : columnnames.get(i)) {
				ExcelUtils.createCell(row, (short) col++, wbStyles.get("header"), XSSFCell.CELL_TYPE_STRING, columnname);
			}
			int lineNum = 1;
			for (int j = 0; j < ldatas.get(i).size(); j++) {
				List<String> rowDatas = ldatas.get(i).get(j);
				Row rowl = sheet.createRow((short) (lineNum++));
				col = 0;
				for (String data : rowDatas) {
					ExcelUtils.createCell(rowl, (short) col++, wbStyles.get("normal"), XSSFCell.CELL_TYPE_STRING, data);
				}
			}
			i++;
		}

	}

	private void generalSheet(Workbook workbook, Map<String, CellStyle> wbStyles, String sheetName, int start, int end,
			List<String> columnnames, List<List<String>> datas) {
		Sheet sheet = workbook.createSheet(sheetName);

		// 设置列宽
		int col = 0;
		if (columnnames != null) {
			for (String columnname : columnnames) {
				sheet.setColumnWidth((short) col++, 5000);
			}
		}

		if (end > start) {
			// 创建第一行标题
			Row row = sheet.createRow((short) 0);
			col = 0;
			for (String columnname : columnnames) {
				ExcelUtils
						.createCell(row, (short) col++, wbStyles.get("header"), XSSFCell.CELL_TYPE_STRING, columnname);
			}
			int lineNum = 1;
			for (int i = start; i < end; i++) {
				List<String> rowDatas = datas.get(i);
				Row rowl = sheet.createRow((short) (lineNum++));
				col = 0;
				int j = 0;
				for (String data : rowDatas) {
					if ("null".equals(data)) {
						data = "";
					}
					if (j == 0) {
						ExcelUtils.createCell(rowl, (short) col++, wbStyles.get("normal"), XSSFCell.CELL_TYPE_STRING,
								data);
					} else {
						try {
							Double.valueOf(data);
							ExcelUtils.createCell(rowl, (short) col++, wbStyles.get("normal"),
									XSSFCell.CELL_TYPE_NUMERIC, data);
						} catch (Exception e) {
							ExcelUtils.createCell(rowl, (short) col++, wbStyles.get("normal"),
									XSSFCell.CELL_TYPE_STRING, data);
						}
					}
					j++;
				}
			}
		}
	}
}
